<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Context\ApplicationContext;
use Throwable;
use Psr\Log\LoggerInterface;
use Hyperf\Logger\LoggerFactory;

#[AutoController]
class IndexController extends AbstractController
{
    protected $redis;
    protected LoggerInterface $logger;
    
    public function __construct(LoggerFactory $loggerFactory)
    {
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        $this->logger = $loggerFactory->get('log', 'test');
    }
    
    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();
        $this->logger->info("Your log message.");
        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }

    //获取普通商品和抢购商品
    public function getIndexProduct()
    {
        try {
            $productNormal = $this->redis->keys('product:normal:*');
            $productSpike = $this->redis->keys('product:spike:*');
            $productListNormal = [];
            $productListSpike = [];
            $productListAll = [];
            foreach ($productNormal as $key) {
                $product = $this->redis->hgetall($key);
                array_push($productListNormal, $product);
            }
            foreach ($productSpike as $key) {
                $product = $this->redis->hgetall($key);
                array_push($productListSpike, $product);
            }
            $productListAll['normal'] = $productListNormal;
            $productListAll['spike'] = $productListSpike;
            return json_encode(['err' => 0, 'msg' => '获取成功', 'productList' => $productListAll]);
        } catch (Throwable $e) {
            return json_encode(['err' => 1, 'msg' => $e->getMessage()]);
        }
    }
}
